<template>
  <div class="add_spot">
    <el-card style="padding: 0 400px">
      <el-steps :active="stepsActive" finish-status="success">
        <el-step title="景区信息" description="填写景区基本信息"></el-step>
        <el-step title="景区介绍" description="填写详细的景区内容"></el-step>
      </el-steps>
    </el-card>

    <el-card class="box-card" style="margin-top: 20px" v-if="stepsActive == 0">
      <div slot="header" style="padding-bottom: 20px">
        <span>新增</span>
        <div style="float: right">
          <el-button size="mini" type="primary" @click="toNextForm"
            >下一步</el-button
          >
          <el-button size="mini" @click="resetOneForm">取消</el-button>
        </div>
      </div>
      <div class="top">
        <p>基本信息</p>
      </div>
      <div class="bottom">
        <el-form
          :model="baseFrom"
          :rules="baseFromRules"
          ref="baseFromRef"
          label-width="100px"
          label-position="top"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="景区名称" prop="jingquName">
                <el-input
                  placeholder="请输入景区名称"
                  v-model="baseFrom.jingquName"
                  clearable
                  size="mini"
                ></el-input> </el-form-item
            ></el-col>
            <el-col :span="12">
              <el-form-item label="景区地址" prop="jingquAddress">
                <el-input
                  placeholder="请输入景区地址"
                  v-model="baseFrom.jingquAddress"
                  clearable
                  size="mini"
                ></el-input> </el-form-item
            ></el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="位置经度" prop="lon">
                <el-input
                  placeholder="请输入位置经度"
                  v-model="baseFrom.lon"
                  clearable
                  size="mini"
                ></el-input> </el-form-item
            ></el-col>
            <el-col :span="12">
              <el-form-item label="位置纬度" prop="lat">
                <el-input
                  placeholder="请输入位置纬度"
                  v-model="baseFrom.lat"
                  clearable
                  size="mini"
                ></el-input> </el-form-item
            ></el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="开园时间" prop="time">
                <el-time-picker
                  format="HH:mm"
                  value-format="HH:mm"
                  is-range
                  arrow-control
                  v-model="baseFrom.time"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  placeholder="选择时间范围"
                >
                </el-time-picker> </el-form-item
            ></el-col>
            <el-col :span="12">
              <el-form-item label="景区类型" prop="type">
                <el-select v-model="baseFrom.type" placeholder="请选择">
                  <el-option
                    v-for="item in jingQType"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="标签" prop="jingquTips">
                <el-tag
                  style="margin-right: 10px"
                  :key="tag"
                  v-for="tag in baseFrom.jingquTips"
                  closable
                  :disable-transitions="false"
                  @close="handleDelTag(tag)"
                >
                  {{ tag }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="inputVisible"
                  v-model="inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm"
                  @blur="handleInputConfirm"
                >
                </el-input>
                <el-button
                  v-if="!inputVisible && baseFrom.jingquTips.length < 3"
                  class="button-new-tag"
                  size="small"
                  @click="showInput"
                  >+ 添加新标签</el-button
                >
              </el-form-item></el-col
            >
            <el-col :span="12">
              <el-form-item label="状态">
                <el-switch
                  v-model="baseFrom.jingquStatus"
                  active-color="#13ce66"
                  inactive-color="#d0d0d0"
                >
                </el-switch>
                <span>{{ baseFrom.jingquStatus ? "开启" : "关闭" }}</span>
              </el-form-item></el-col
            >
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="景区图片" prop="jingquPictureUrl">
                <div v-if="!baseFrom.jingquPictureUrl">
                  <el-upload
                    :action="uploadUrl"
                    list-type="picture-card"
                    :before-upload="handleBeforeUpload"
                    :on-success="handleUploadSuccess"
                    :on-error="handleUploadError"
                    :on-remove="onRemoveHandel"
                    :headers="headers"
                    ref="upload"
                    :limit="1"
                  >
                    <i class="el-icon-plus"></i>
                  </el-upload>
                  <p style="color: red; font-size: 14px">
                    提示：推荐尺寸为750*500，图像大小≤8M，格式为jpg，png，jpeg
                  </p>
                </div>
                <div v-else style="position: relative">
                  <el-image
                    style="width: 100px; height: 100px"
                    :src="baseFrom.jingquPictureUrl"
                    :preview-src-list="[baseFrom.jingquPictureUrl]"
                  >
                  </el-image>
                  <i class="el-icon-error" @click="onRemoveHandel"></i>
                </div> </el-form-item
            ></el-col>
            <!-- <el-col :span="12">
              </el-col
            > -->
          </el-row>
        </el-form>
      </div>
    </el-card>

    <el-card class="box-card" style="margin-top: 20px" v-if="stepsActive == 1">
      <div slot="header" style="padding-bottom: 20px">
        <span>新增</span>
        <div style="float: right">
          <el-button size="mini" type="primary" @click="toThreeForm"
            >确定</el-button
          >
          <el-button size="mini" @click="toOneForm">上一步</el-button>
        </div>
      </div>
      <div class="top">
        <p>景区介绍</p>
      </div>
      <div class="bottom">
        <editor v-model="baseFrom.jingquText" :min-height="192" />
      </div>
    </el-card>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import {
  addjingQuApi, // 新增景区
  updatejingQuApi, // 修改景区
  getJingTypeApi,
} from "@/api/YApi/scenicSpot";

export default {
  props: {},
  computed: {},
  data() {
    return {
      jingQType: [],
      allData: {}, // 保存所有数据
      // 文件上传
      uploadUrl: window.serverAPI.url + "/common/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      uploadFileLoading: false,

      backObj: {}, // 回显的数据
      isEdit: false,

      // 标签
      inputVisible: false,
      inputValue: "",

      stepsActive: 0,
      // 基本信息
      baseFrom: {
        jingquName: "",
        jingquAddress: "",
        time: "",
        jingquTips: [],
        jingquPictureUrl: "",
        jingquStatus: false,
        jingquText: "",
        lon: "",
        lat: "",
        type: "",
      },
      baseFromRules: {
        jingquName: [
          { required: true, message: "请输入景区名称", trigger: "blur" },
        ],
        jingquAddress: [
          { required: true, message: "请输入景区地址", trigger: "blur" },
        ],
        lon: [
          { required: true, message: "请输入景区位置经度", trigger: "blur" },
        ],
        lat: [
          { required: true, message: "请输入景区位置纬度", trigger: "blur" },
        ],
        time: [
          {
            required: true,
            message: "请选择开始时间和结束时间",
            trigger: "change",
          },
        ],
        type: [
          {
            required: true,
            message: "请选择景区类型",
            trigger: "change",
          },
        ],
        jingquTips: [
          { required: true, message: "请添加景区标签", trigger: "blur" },
        ],
        jingquPictureUrl: [
          { required: true, message: "请选择景区图片", trigger: "change" },
        ],
      },
    };
  },
  created() {
    this.isChangeFun(this.$router);
    this.getJingTypeFun();
  },

  methods: {
    getJingTypeFun() {
      getJingTypeApi()
        .then((res) => {
          console.log(res);
          if (res.code === 200) {
            this.jingQType = res.data;
          } else {
            this.jingQType = [];
          }
        })
        .catch((err) => {
          console.log(err);
          this.jingQType = [];
        });
    },
    // 判断是新增还是修改
    isChangeFun(routerInfo) {
      const action = routerInfo.history.current.query.action;
      if (action == "edit") {
        const row = JSON.parse(routerInfo.history.current.query.row);
        this.isEdit = true;
        this.backObj = row;
        console.log(row);
        // 第一页的数据
        this.baseFrom.jingquName = row.jingquName;
        this.baseFrom.jingquAddress = row.jingquAddress;
        this.baseFrom.time = [row.jingquOpenTime, row.jingquCloseTime];
        this.baseFrom.jingquTips = row.jingquTips.split(",");
        this.baseFrom.jingquPictureUrl = row.jingquPictureUrl;
        this.allData.jingquPictureUrl = row.jingquPictureUrl;
        this.baseFrom.jingquStatus = row.jingquStatus == 1 ? false : true;
        this.baseFrom.type = row.type;

        this.baseFrom.lat = row.lat;
        this.baseFrom.lon = row.lon;

        // 第二页的数据
        this.baseFrom.jingquText = row.jingquText;
      }
    },
    reset() {
      this.allData = {};
    },

    // 填完第二页
    toThreeForm() {
      this.allData.jingquText = this.baseFrom.jingquText;
      if (this.isEdit) {
        this.allData.jingquId = this.backObj.jingquId;
        updatejingQuApi(this.allData)
          .then((res) => {
            console.log(res);
            if (res.code === 200) {
              this.msgSuccess("修改成功");
              this.reset();
              this.$router.replace({
                name: "/publicService/scenicSpot",
              });
            } else {
              this.msgError("修改失败");
            }
          })
          .catch((err) => {
            this.msgError("修改失败");
            console.log(err);
            this.reset();
          });
      } else {
        addjingQuApi(this.allData)
          .then((res) => {
            console.log(res);
            if (res.code === 200) {
              this.msgSuccess("新增成功");
              this.reset();
              this.$router.replace({
                name: "/publicService/scenicSpot",
              });
            } else {
              this.msgError("新增失败");
            }
          })
          .catch((err) => {
            this.msgError("新增失败");
            console.log(err);
            this.reset();
          });
      }
    },
    // 返回第一页
    toOneForm() {
      this.allData.jingquText = "";
      this.baseFrom.jingquText = "";
      this.stepsActive = 0;
    },
    // 取消第一页的from
    resetOneForm() {
      this.$refs.baseFromRef.resetFields();
      this.baseFrom = {
        jingquName: "",
        jingquAddress: "",
        time: "",
        jingquTips: [],
        jingquPictureUrl: "",
        jingquStatus: false,
        jingquText: "",
      };
      this.allData = {};
    },
    // 从第一页跳转到第二页
    toNextForm() {
      console.log(this.baseFrom.time);
      this.$refs.baseFromRef.validate((valid) => {
        if (valid) {
          this.allData = {
            jingquName: this.baseFrom.jingquName,
            jingquAddress: this.baseFrom.jingquAddress,
            jingquOpenTime: this.baseFrom.time[0],
            jingquCloseTime: this.baseFrom.time[1],
            jingquTips: this.baseFrom.jingquTips.join(","),
            jingquPictureUrl: this.baseFrom.jingquPictureUrl,
            jingquStatus: this.baseFrom.jingquStatus ? 0 : 1, // 0是开启 1是关闭
            lat: this.baseFrom.lat,
            lon: this.baseFrom.lon,
            type: this.baseFrom.type,
          };
          console.log(this.allData);
          this.stepsActive = 1;
          if (this.isEdit) {
            const row = JSON.parse(this.$router.history.current.query.row);
            this.baseFrom.jingquText = row.jingquText;
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 标签
    handleDelTag(tag) {
      this.baseFrom.jingquTips.splice(this.baseFrom.jingquTips.indexOf(tag), 1);
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.baseFrom.jingquTips.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = "";
    },

    // 文件上传函数
    // 使用 before-upload 限制用户上传的图片格式和大小。
    handleBeforeUpload(file) {
      console.log(file);
      // 校检文件大小
      const isLt = file.size / 1024 / 1024 < 8;
      if (!isLt) {
        this.$message.error(`上传文件大小不能超过8MB!`);
        return false;
      }
      // 检验格式
      let type = file.type;
      let jpg = type.indexOf("jpg");
      let png = type.indexOf("png");
      let jpeg = type.indexOf("jpeg");
      if (jpg == -1 && png == -1 && jpeg == -1) {
        this.$message.error(`上传文件格式为jpg，png，jpeg!`);
        return false;
      }

      return true;
    },

    // 文件上传成功钩子
    handleUploadSuccess(response, file, fileList) {
      console.log(response, file, fileList);
      if (response.code === 200) {
        this.baseFrom.jingquPictureUrl = response.data.url;
        this.allData.jingquPictureUrl = response.data.url;
        // 手动触发fileList校验规则
        this.$refs.baseFromRef.validate("jingquPictureUrl");
      }
    },

    // 删除已上传的文件
    onRemoveHandel() {
      this.baseFrom.jingquPictureUrl = "";
      this.allData.jingquPictureUrl = "";
    },

    // 文件上传失败
    handleUploadError() {
      this.$message.error("图片插入失败");
    },
  },
};
</script>
<style lang="scss" scoped>
.add_spot {
  padding: 20px;
}
::v-deep .el-form-item {
  margin-bottom: 20px !important;
}
::v-deep .el-form-item__label {
  padding: 0 !important;
}

.top {
  height: 18px;
  font-size: 16px;
  font-weight: 400;
  color: #333333;
  line-height: 19px;
  border-left: 4px solid #3370ff;
  padding-left: 8px;
  margin-bottom: 10px;
}
.el-icon-error {
  position: absolute;
  left: 88px;
  cursor: pointer;
  &:hover {
    color: red;
  }
}
</style>
